#!/usr/bin/env bash

#
# NOTE: Maintains the OS, backup, docker, software etc.
#


# 1. reserve disk space.
# 1.1 /var/log
function clearOSLog()
{
  pushd /var/log
  rm -f *.gz
  rm -f *-????????
  popd
}

# 2. k8s
# 2.2 k8s rs
function clearK8SRS()
{
  kubectl get rs -A | awk '/0\ .*0\ .*0\ .*/{cmd="kubectl -n "$1" delete rs "$2; system(cmd)}'
}

# 2.1 k8s log
function clearK8SLog()
{
  local -ra LOGGER=(INFO WARNING FATAL ERROR)
  local -r HOSTNAME=$(hostname -s)
  local TYPE="kubelet"

  pushd /appdata/k8s/kubelet
  for logger in ${LOGGER[@]}; do
    ls -t1 ${TYPE}.${HOSTNAME}.${USER}.log.${logger}.* | awk 'NR>1{print $1}' | xargs rm -f
  done
  popd

  pushd /appdata/k8s/controller
  TYPE="kube-controller-manager"
  for logger in ${LOGGER[@]}; do
    ls -t1 ${TYPE}.${HOSTNAME}.${USER}.log.${logger}.* | awk 'NR>1{print $1}' | xargs rm -f
  done
  popd
}

# 3 docker
function clearDocker()
{
  # remove docker images and files unused.
  echo "clearDocker"
}

# 4 backup file
function clearBackup()
{
  # number of remain backup copies.
  local -r DAYS=7

  pushd /appdata/ghxt/archive
  ls -t1 archive.* | awk "NR>${DAYS}{print \$0}" | xargs rm -f
  popd

  pushd /appdata/ghxt/ghxt_fi
  ls -t1 ghxt_fi.* | awk "NR>${DAYS}{print \$0}" | xargs rm -f
  popd
}


#### ---- main
set -ex
clearOSLog

clearK8SRS
clearK8SLog

#clearBackup
